<template>
  <a-modal title="导入EXCEL" :width="600" :visible="visible" :confirmLoading="uploading" @cancel="handleClose">
    <div style="margin: 0px 0px 5px 1px" v-if="online">
      <span style="display: inline-block; height: 32px; line-height: 32px; vertical-align: middle">是否开启校验:</span>
      <span style="display: inline-block; height: 32px; margin-left: 6px">
        <a-switch
          :checked="validateStatus == 1"
          @change="handleChangeValidateStatus"
          checked-children="是"
          un-checked-children="否"
          size="small"
        />
      </span>
    </div>

    <a-upload
      name="file"
      :multiple="false"
      accept=".xls,.xlsx,.csv"
      :fileList="fileList"
      :remove="handleRemove"
      :beforeUpload="beforeUpload"
    >
      <a-button>
        <a-icon type="upload" />
        选择导入文件
      </a-button>
    </a-upload>

    <template slot="footer">
      <a-button @click="handleClose">关闭</a-button>
      <a-button type="primary" @click="handleImport" :disabled="fileList.length === 0" :loading="uploading">
        {{ uploading ? '上传中...' : '开始上传' }}
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import { axios } from '@/utils/request'
import * as XLSX from 'xlsx/xlsx.mjs'
import X2js from 'x2js'

export default {
  name: 'JImportModal',
  props: {
    url: {
      type: String,
      default: '',
      required: false
    },
    biz: {
      type: String,
      default: '',
      required: false
    },
    value: {
      type: Array,
      default: () => [],
      required: false
    },
    // 是否online导入
    online: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      visible: false,
      uploading: false,
      fileList: [],
      jsonDict: [],

      uploadAction: '',
      foreignKeys: '',
      validateStatus: 0,
      properties: [],
      geoProperties: [
        {
          _ID: 'TZ_GXSX',
          _Label: '排水管线段'
        }
      ]
    }
  },
  // watch: {
  //   url(val) {
  //     if (val) {
  //       this.uploadAction = window._CONFIG['domianURL'] + val
  //     }
  //   }
  // },
  created() {
    const formData = new FormData()
    formData.append('rows', 60)
    formData.append('page', 1)
    formData.append('sidx', 'to_number(TableId)')
    formData.append('sord', 'asc')
    // this.uploadAction = window._CONFIG['domianURL'] + this.url
    // postAction("http://183.250.128.116:5093/Web_Api/Config/RequestXwTabInfoData", formData).then(res => {
    //   console.log(res)
    // })
    axios({
      baseURL: '/',
      url: '/data/GetAllDictByTableSpace.json',
      method: 'get'
    }).then((res) => {
      const x2js = new X2js()
      // 将xml解析为我们需要的json对象
      const json = x2js.xml2js(res.d)
      this.jsonDict = json.Result.Table
      console.log(json)
    })
  },

  methods: {
    handleClose() {
      this.visible = false
    },
    show(arg) {
      this.fileList = []
      this.uploading = false
      this.visible = true
      this.foreignKeys = arg
      this.validateStatus = 0
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    // beforeUpload(file) {
    //   this.fileList = [...this.fileList, file]
    //   return false
    // },
    // 导入前条件处理
    beforeUpload(file) {
      // if (!this.supplierInfo.supCode) {
      //   this.confirmLoading = false
      //   return this.KaTeX parse error: Expected 'EOF', got '}' at position 32: …择供货商') }̲ else if (!this…message.info(‘请选择仓库’)
      // }

      this.fileList = [...this.fileList, file]
      // TODO
      // 换行和空格 “成果上游井编号”   “断面尺寸2”
      // 时间格式校验
      //
      this.readExcel(file, this, this.properties).then((workbook) => {
        this.properties = this.jsonDict.filter((item) => {
          return workbook.SheetNames.includes(item._Label)
        })
        console.log(this.jsonDict)
        console.log(this.properties)
        const dataSources = []
        const panes = []
        this.properties.map((item, idx) => {
          const pane = {}
          pane.title = item._Label
          pane.key = idx
          pane.name = item._ID
          const ws = workbook.Sheets[item._Label]
          const opts = {
            range: 6,
            header: []
          }
          var range = XLSX.utils.decode_range(ws['!ref'])
          // for (R = r.s.r + offset; R <= r.e.r; ++R)
          for (var C = range.s.c; C <= range.e.c; ++C) {
            var coord = XLSX.utils.encode_cell({ r: 1, c: C })
            var cell = ws[coord]
            if (!cell || !cell.v) continue
            // clean up raw value of string cells
            if (cell.t == 's') cell.v = cell.v.trim().replace(/\r\n/g, '').replace(/\n/g, '')

            // clean up formatted text
            if (cell.w) cell.w = cell.w.trim().replace(/\r\n/g, '').replace(/\n/g, '')
            opts.header[C] = cell.v
          }
          const columns = []
          item.Field.sort((a, b) => {
            return parseInt(a._Order) - parseInt(b._Order)
          })
          const properties = item.Field.map((property) => {
            const column = {
              title: property._Label,
              key: property._Order,
              width: '80px',
              ellipsis: true,
              dataIndex: property._ID,
              scopedSlots: { customRender: property._ID }
            }
            columns.push(column)
            let description = property._Description
            if (
              typeof property._Description === 'string' &&
              description.trim() != '' &&
              description.indexOf('//') >= 0
            ) {
              description = description.substring(2)
              const strArr = description.split(';').map((string) => {
                return string.split('-')
              })
              property._Description = Object.fromEntries(strArr)
            }
            return property
          })
          const exl = XLSX.utils.sheet_to_json(ws, opts)
          const arr = []
          const testRes = []
          exl.map((v) => {
            const obj = {}
            var tips = []
            properties.map((property, pIdx) => {
              // 时间格式
              if (v[property._Label] != null && v[property._Label] !== '') {
                const val = v[property._Label]
                switch (val instanceof Date) {
                  case true:
                    obj[property._ID] = val.toJSON().substr(0, 10)
                    break
                  default:
                    obj[property._ID] = typeof property._Description === 'object' ? property._Description[val] : val

                    if (property._Type == 'NVARCHAR2') {
                      if (val.length > parseInt(property._Length)) {
                        tips.push(property._Label)
                      }
                    }
                    if (typeof val !== 'number' && property._Type == 'NUMBER') {
                      tips.push(property._Label)
                    }
                    break
                }
              } else {
                obj[property._ID] = null
                // TODO
                //  提示
                // obj[property._ID] = opts.header[pIdx + 1] + ":"+v[opts.header[pIdx +1]]
                if (property._ValidRules == '1') tips.push(property._Label)
              }
            })
            arr.push(obj)
            if ((!v['检测井类别'] || (v['检测井类别'] && v['检测井类别'] < 16)) && tips.length > 0) {
              const otherObj = {}
              Object.assign(otherObj, obj)
              otherObj.tips = tips.join(',')
              testRes.push(otherObj)
            }
          })
          dataSources.push(arr)
          pane.dataSource = arr
          pane.testData = testRes
          pane.columns = columns
          pane.ipagination = {
            pageSize: 10,
            showTotal: (total, range) => {
              return range[0] + '-' + range[1] + ' 共' + total + '条'
            },
            total: pane.dataSource.length
          }
          panes.push(pane)
        })
        // workbook.SheetNames.map(exlname =>{
        // let properties = []
        // let opts = {
        //   range: 6,
        //   header: []
        // }
        // const exlname = workbook.SheetNames[1]
        // const ws = workbook.Sheets[exlname]

        // var range = XLSX.utils.decode_range(ws['!ref']);
        // for(var C = range.s.c; C <= range.e.c; ++C) {
        //   var coord = XLSX.utils.encode_cell({r:1, c:C}), cell = ws[coord];
        //   if(!cell || !cell.v) continue;
        //   // clean up raw value of string cells
        //   if(cell.t == 's') cell.v = cell.v.trim().replace(/\r\n/g, '');
        //   // clean up formatted text
        //   if(cell.w) cell.w = cell.w.trim().replace(/\r\n/g, '');
        //   opts.header[C] = cell.w
        // }
        // const exl = XLSX.utils.sheet_to_json(ws, opts)
        // this.properties.map(item => {
        //   if(item._Label == exlname){
        //     properties = item.Field
        //   }
        // })
        // const arr = []
        // console.log(exl)
        // exl.map(v => {
        //   const obj = {}
        //   properties.map(property => {
        //     obj[property._ID] = v[property._Label]
        //   })
        //   arr.push(obj)
        // })
        // })
        this.$emit('change', panes)
        // this.$emit('change', arr);
        return false
      })
    },
    readExcel(file, that, properties) {
      return new Promise(function (resolve, reject) {
        // 返回Promise对象
        const reader = new FileReader()
        reader.onload = (e) => {
          // 异步执行
          try {
            // 以二进制流方式读取得到整份excel表格对象
            const data = e.target.result
            const workbook = XLSX.read(data, { type: 'binary', cellDates: true, cellFormula: true })
            const exlname = workbook.SheetNames[0]
            // // 取第一张表
            const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname])
            console.log(exl)
            // const arr = []
            // exl.map(v => {
            //   const obj = {}
            //   properties.map(property => {
            //     obj[property.key] = v[property.value]
            //   })
            //   arr.push(obj)
            // })
            // that.exlData = arr
            resolve(workbook)
          } catch (e) {
            reject(e.message)
          }
        }
        reader.readAsBinaryString(file)
      })
    },
    handleImport() {
      const { fileList } = this
      const formData = new FormData()
      if (this.biz) {
        formData.append('isSingleTableImport', this.biz)
      }
      if (this.foreignKeys && this.foreignKeys.length > 0) {
        formData.append('foreignKeys', this.foreignKeys)
      }
      if (this.online == true) {
        formData.append('validateStatus', this.validateStatus)
      }
      fileList.forEach((file) => {
        formData.append('files[]', file)
      })
      this.uploading = true

      // postAction(this.uploadAction, formData).then(res => {
      //   this.uploading = false
      //   if (res.success) {
      //     if (res.code == 201) {
      //       this.errorTip(res.message, res.result)
      //     } else {
      //       this.$message.success(res.message)
      //     }
      const fileNames = this.fileList.map((item) => {
        return item.name
      })
      this.visible = false
      this.$emit('ok', fileNames[0])
      //   } else {
      //     this.$message.warning(res.message)
      //   }
      // })
    },
    // 是否开启校验 开关改变事件
    handleChangeValidateStatus(checked) {
      this.validateStatus = checked == true ? 1 : 0
    },
    // 错误信息提示
    errorTip(tipMessage, fileUrl) {
      const h = this.$createElement
      const href = window._CONFIG['domianURL'] + fileUrl
      this.$warning({
        title: '导入成功,但是有错误数据!',
        content: h('div', {}, [
          h('div', tipMessage),
          h('span', '具体详情请 '),
          h(
            'a',
            {
              attrs: {
                href: href,
                target: '_blank'
              }
            },
            '点击下载'
          )
        ]),
        onOk() {}
      })
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}
</script>

<style scoped></style>
